package com.rpcfx.server;


import com.rpcfx.api.RpcfxException;
import com.rpcfx.api.RpcfxRequest;
import com.rpcfx.api.RpcfxResolver;
import com.rpcfx.api.RpcfxResponse;

import java.lang.reflect.InvocationTargetException;

public class RpcfxInvoker {

    private RpcfxResolver resolver;

    public RpcfxInvoker(RpcfxResolver resolver) {
        this.resolver = resolver;
    }

    public RpcfxResponse invoke(RpcfxRequest request) {
        RpcfxResponse response = new RpcfxResponse();
        String serviceClass = request.getServiceClass();

        // 作业1：改成泛型和反射
        Object service = resolver.resolve(serviceClass);//this.applicationContext.getBean(serviceClass);

        try {

            ReflectiveInvoker reflectiveInvoker = new ReflectiveInvoker(service);
            Object result = reflectiveInvoker.invoke(request.getMethod(), request.getParams());
            response.setData(result);
            response.setSuccess(true);
            return response;
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            RpcfxException rpcfxException = new RpcfxException(-1, e.getMessage());
            response.setRpcfxException(rpcfxException);
            response.setSuccess(false);
            return response;
        }
    }

}
